<template>
  <div>
    <el-form
      ref="ruleForm"
      :model="ruleForm"
      label-width="100px"
      class="demo-ruleForm"
      :rules="rules"
    >
      <el-form-item label="姓名" prop="username">
        <el-input v-model="ruleForm.username" />
      </el-form-item>
      <el-form-item label="手机号" prop="mobile">
        <el-input v-model="ruleForm.mobile" />
      </el-form-item>
      <el-form-item label="入职时间" required>
        <el-col>
          <el-date-picker
            v-model="ruleForm.timeOfEntry"
            type="date"
            format="yyyy年MM月dd日"
            value-format="yyyy--MM--dd"
            placeholder="选择日期"
            style="width: 100%"
          />
        </el-col>
      </el-form-item>
      <el-form-item label="聘用形式" prop="formOfEmployment">
        <el-select
          v-model="ruleForm.formOfEmployment"
          placeholder="请选择活动区域"
        >
          <!--   <el-option label="正式" value="shanghai" /> -->
          <el-option
            v-for="item in ConstantEnum.hireType"
            :key="item.id"
            :label="item.value"
            :value="item.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="工号" prop="workNumber">
        <el-input v-model="ruleForm.workNumber" />
      </el-form-item>
      <el-form-item label="部门" prop="departmentName">
        <!-- 当你写代码发现,写不下去,一般是缺少了变量,需要增加变量 -->
        <el-input v-model="ruleForm.departmentName" @focus="isShowTree=true" />
        <!-- 树形结构 -->
        <transition name="fade">
          <el-tree v-if="isShowTree" :data="data" :props="defaultProps" @node-click="handleNodeClick" />
        </transition>
      </el-form-item>
      <el-form-item label="转正时间" required>
        <el-col>
          <el-date-picker
            v-model="ruleForm.correctionTime"
            type="date"
            placeholder="选择日期"
            style="width: 100%"
          />
        </el-col>
      </el-form-item>
      <el-form-item>
        <el-button
          type="primary"
          @click="submitForm"
        >立即创建</el-button>
        <el-button @click="resetForm">取消</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import ConstantEnum from '@/constant/employees'
import { valideMobile } from '@/utils/validate'
import { addUserRequest } from '@/api/employees'
import { getDepartmentInfoReqest } from '@/api/department'
import { transformListToTree2 } from '@/utils'
export default {
  name: 'VueHr85DialogForm',
  data() {
    const validateMobile = (rule, value, callback) => {
      // 正则校验手机号
      if (!valideMobile(value)) {
        callback(new Error('密码格式不对'))
      } else {
        callback()
      }
    }
    return {
      isShowTree: false,
      data: [],
      defaultProps: {
        children: 'children',
        label: 'name'
      },
      // 导入的变量如果要直接使用到template模板里面,是没有响应式的
      // 需要在data里面在定义一下,然后vue会进行数据劫持,才会有响应式
      ConstantEnum: ConstantEnum,
      ruleForm: {
        username: '',
        mobile: '',
        timeOfEntry: '',
        formOfEmployment: '',
        workNumber: '',
        departmentName: '',
        correctionTime: ''
      },
      rules: {
        username: [
          { required: true, message: '请输入活动名称', trigger: 'blur' },
          { min: 2, max: 4, message: '长度在 2 到 4 个字符', trigger: 'blur' }
        ],
        mobile: [
          { required: true, message: '请输入活动名称', trigger: 'blur' },
          { validator: validateMobile, trigger: 'change' }
        ],
        formOfEmployment: [
          {
            required: true,
            message: '请至少选择一个活动性质',
            trigger: 'change'
          }
        ],
        workNumber: [
          { required: true, message: '请输入活动名称', trigger: 'blur' },
          { min: 3, max: 5, message: '长度在 3 到 5 个字符', trigger: 'blur' }
        ],
        departmentName: [
          { required: true, message: '请输入活动名称', trigger: 'change' }
          // { min: 3, max: 5, message: '长度在 3 到 5 个字符', trigger: 'blur' }
        ]
      }
    }
  },
  created() {
    this.getDepartment()
  },
  methods: {
    async addUser() {
      try {
        const res = await addUserRequest(this.ruleForm)
        if (res.success) {
        // 业务成功
        } else {
        // 业务失败
          return this.$message.error('新增员工失败')
        }
        this.$emit('upDate')
      } catch (err) {
        console.log('addUserRequest:', err)
      }
    },
    submitForm() {
      this.$refs.ruleForm.validate(val => {
        if (val) {
          this.addUser()
        }
      })
    },
    resetForm(formName) {
      this.$emit('update:dialogVisible', false)
    },
    handleNodeClick(val) {
      console.log(val)
      if (val.children?.length >= 1) {
        return
      }
      this.ruleForm.departmentName = val.name
      // 关闭部门的tree
      this.isShowTree = false
    },
    async getDepartment() {
    //   async await 就是把异步的代码，当初同步的形式来写
      try {
        const res = await getDepartmentInfoReqest()
        res.data.depts.shift()
        this.data = transformListToTree2(res.data.depts, '')
        console.log('getDepartmentInfoReqest', res)
      } catch (err) {
        console.log('getDepartmentInfoReqest', err)
      }
      // async是es8 2017年的语法， promise是es6 2015年的语法， 2015年之前是回调函数的写法
    //   getDepartmentInfoReqest().then(res => {
    //     // then有两个参数，都是函数，第一个函数是 请求成功后执行，第二个函数是请求失败后执行
    //     console.log('请求成：', res)
    //     // forEach filter map  reduce复杂 --- 函数的参数和函数的返回值
    //     // some every 数组循环次数 并不一定是数组的长度的次数
    //     // this.arrListToChild = res.data.depts.map(item => ({name: xxx}))
    //     this.arrListToChild = res.data.depts.map(item => {
    //       return {
    //         id: item.id,
    //         pid: item.pid,
    //         name: item.name,
    //         code: item.code
    //       }
    //     })
    //     this.companyInfo = res.data.depts.shift()
    //     // this.data = res.data.depts
    //     // this.data = transformListToTree(res.data.depts)
    //     // this.data = transformListToTree(res.data.depts, '')
    //   }, err => {
    //     console.log('请求失败：', err)
    //   })
    }
  }
}
</script>

<style lang="scss" scoped>
 .fade-enter-active, .fade-leave-active {
  transition: opacity .5s;
}
.fade-enter, .fade-leave-to /* .fade-leave-active below version 2.1.8 */ {
  opacity: 0;
}
</style>

